package com.yswy.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yswy.app.dto.domianVo.PackageManageVo;
import com.yswy.app.service.IpPlaceService;
import com.yswy.app.service.SysConfigService;
import com.yswy.domain.common.util.BaiduIpApi;
import com.yswy.common.utils.redis.RedisConstants;
import com.yswy.common.utils.redis.RedisUtil;
import com.yswy.domain.entity.*;
import com.yswy.domain.mapper.IpPlaceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.zip.CRC32;

@Service
@Slf4j
public class IpPlaceServiceImpl extends ServiceImpl<IpPlaceMapper, IpPlace>
        implements IpPlaceService {
    @Autowired
    private RedisUtil redisUtil ;
    @Autowired
    private SysConfigService sysConfigService ;
    @Override
    public IpPlace getIpPlace(String ip) {
        //查询是否存在ip
        IpPlace ipPlace = null ;
        String key = RedisConstants.IpPlace+ip ;
        if (redisUtil.hasKey(key)){
            ipPlace = (IpPlace)redisUtil.getObejct(key);
        }else {
            CRC32 crc32 = new CRC32();
            crc32.update(ip.getBytes());
            Long createIpCrc = crc32.getValue();
            ipPlace = getOne(new LambdaQueryWrapper<IpPlace>()
                    .eq(IpPlace::getCreateIpCrc , createIpCrc)
                    .last("limit  1"));
        }
        if (ipPlace == null){
            //查询ip归属地
            ipPlace = BaiduIpApi.getIpPlace(ip);
            save(ipPlace);
            System.out.println("ssssss");
        }
        ipPlace.setCreateTime(null);
        redisUtil.setForObjectTimeCustom(key, ipPlace, 30, TimeUnit.DAYS);

        return ipPlace;
    }

    @Override
    public boolean getIpPlaceStatus(String ip) {
        //查询是否存在ip
        String phones = sysConfigService.selectConfigByKey("disable_city");
        phones = phones.replaceAll(" ", "");
        String[] split = phones.split(",");
        IpPlace ipPlace = getIpPlace(ip);
        for (String s:split) {
            if (ipPlace.getPlaceDatas().contains(s)){
                return true ;
            }
        }
        return false;
    }
}
